import {createWithEqualityFn} from "zustand/traditional";
import {ChannelAPI} from "@/apis";
import {useEffect} from "react";

// 关于counter的store切片
const createCounterStore = createWithEqualityFn((set) => {
    return {
        count: 0,
        increment: () => set((state) => ({count: state.count + 1})),
    }
})
// 关于channels的store切片
const createChannelStore = createWithEqualityFn((set) => {
    return {
        datalist: [],
        // 异步请求数据
        FetchData: async () => {
            const res = await ChannelAPI()
            set({datalist: res.data.channels})
        }

    }
})
// 组合切片
const useStoreWithEqualityFn = createWithEqualityFn((...a) => {
    return {
        ...createCounterStore(...a),
        ...createChannelStore(...a)
    }
})

function AppZustand() {
    const {count, increment, datalist, FetchData} = useStoreWithEqualityFn();
    useEffect(() => {
        FetchData()
    }, [datalist]);
    return (
        <div>
            <div>
                <button onClick={increment}>{count}</button>
            </div>
            <div>
                <ul>
                    {datalist.map(item => <li key={item.id}>{item.name}</li>)}
                </ul>
            </div>
        </div>
    )
}

export default AppZustand;